package com.controller.lib.upgrade

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import com.controller.lib.utils.SystemUtils
import timber.log.Timber

/**
 * author : gerui
 * date   : 2021/9/7 10:09
 * desc   :
 * version: 1.0
 */
class NetWorkListener(
  /**
   * 网络变化回调
   */
  private val callBack: NetWorkChangeCallBack?
) {
  /**
   * 网络变化广播
   */
  private var networkChange: NetWorkChangeReceiver? = null

  /**
   * 注册网络监听
   */
  fun registerNetWorkReceiver(context: Context) {
    Timber.i("registerNetWorkReceiver")
    val intentFilter = IntentFilter()
    intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE")
    if (networkChange == null) {
      networkChange = NetWorkChangeReceiver()
      context.registerReceiver(networkChange, intentFilter)
    }
  }

  /**
   * 解除网络监听
   */
  fun unRegisterNetWorkReceiver(context: Context) {
    Timber.i("unRegisterNetWorkReceiver")
    if (networkChange != null) {
      context.unregisterReceiver(networkChange)
    }
  }

  /**
   * 网络变化广播
   */
  internal inner class NetWorkChangeReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
      val specialNetType = SystemUtils.getSpecialNetType(context)
      val isConnected = SystemUtils.isConnected(specialNetType)
      Timber.i("onReceive_%s,%s", specialNetType, isConnected)

      callBack?.onNetWorkChanged(specialNetType, isConnected)
    }
  }

  /**
   * 网络变化回调
   */
  interface NetWorkChangeCallBack {
    /**
     * 网络变化回调
     *
     * @param networkType 网络类型
     * @param available 网络是否可用
     */
    fun onNetWorkChanged(networkType: Int, available: Boolean)
  }
}
